<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Phantoms成员动态</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            font-family: 'Segoe UI', 'Microsoft YaHei', sans-serif;
        }

        /* 美化滚动条 */
        ::-webkit-scrollbar {
            width: 10px;
        }

        ::-webkit-scrollbar-track {
            background: #404040;
            border-radius: 5px;
        }

        ::-webkit-scrollbar-thumb {
            background: #707070;
            border-radius: 5px;
            border: 2px solid #404040;
        }

        ::-webkit-scrollbar-thumb:hover {
            background: #808080;
        }

        /* Firefox滚动条样式 */
        html {
            scrollbar-width: thin;
            scrollbar-color: #707070 #404040;
        }

        body {
            background-color: #1a1a1a;
            color: #e0e0e0;
            line-height: 1.6;
            padding: 20px;
            overflow-x: hidden;
        }

        .container {
            max-width: 1200px;
            margin: 0 auto;
        }

        header {
            text-align: center;
            margin-bottom: 30px;
            padding: 25px;
            background: linear-gradient(135deg, #2a2a2a 0%, #3a3a3a 100%);
            border-radius: 12px;
            box-shadow: 0 6px 20px rgba(0, 0, 0, 0.4);
            border: 1px solid #404040;
        }

        h1 {
            font-size: 2.8rem;
            margin-bottom: 10px;
            color: #ffffff;
            text-shadow: 0 2px 8px rgba(0, 0, 0, 0.5);
            letter-spacing: 1px;
        }

        .subtitle {
            font-size: 1.3rem;
            color: #b0b0b0;
            font-weight: 300;
        }

        .controls {
            display: flex;
            justify-content: space-between;
            margin-bottom: 25px;
            flex-wrap: wrap;
            gap: 15px;
        }

        .filter-controls {
            display: flex;
            gap: 12px;
            flex-wrap: wrap;
        }

        select, button {
            padding: 12px 18px;
            border: none;
            border-radius: 8px;
            background-color: #404040;
            color: #f0f0f0;
            cursor: pointer;
            transition: all 0.3s ease;
            font-size: 1rem;
            border: 1px solid #555;
        }

        select:hover, button:hover {
            background-color: #505050;
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3);
        }

        button {
            background-color: #606060;
            font-weight: 600;
        }

        button:hover {
            background-color: #707070;
        }

        .stats {
            display: flex;
            justify-content: space-around;
            background-color: #2a2a2a;
            padding: 20px;
            border-radius: 12px;
            margin-bottom: 25px;
            flex-wrap: wrap;
            border: 1px solid #404040;
            box-shadow: 0 4px 15px rgba(0, 0, 0, 0.3);
        }

        .stat-item {
            text-align: center;
            padding: 15px;
        }

        .stat-value {
            font-size: 2.5rem;
            font-weight: bold;
            color: #ffffff;
            text-shadow: 0 2px 4px rgba(0, 0, 0, 0.5);
        }

        .stat-label {
            font-size: 1rem;
            color: #b0b0b0;
            margin-top: 5px;
        }

        .activity-list {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(360px, 1fr));
            gap: 25px;
        }

        .activity-card {
            background: linear-gradient(145deg, #2a2a2a, #333333);
            border-radius: 12px;
            padding: 25px;
            transition: all 0.3s ease;
            box-shadow: 0 6px 15px rgba(0, 0, 0, 0.3);
            cursor: pointer;
            border: 1px solid #404040;
            position: relative;
            overflow: hidden;
        }

        .activity-card::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 4px;
            background: linear-gradient(90deg, #808080, #a0a0a0);
        }

        .activity-card:hover {
            transform: translateY(-8px);
            box-shadow: 0 12px 25px rgba(0, 0, 0, 0.4);
        }

        .activity-header {
            display: flex;
            align-items: center;
            margin-bottom: 18px;
        }

        .avatar {
            width: 65px;
            height: 65px;
            border-radius: 50%;
            object-fit: cover;
            margin-right: 18px;
            border: 3px solid #707070;
            box-shadow: 0 3px 10px rgba(0, 0, 0, 0.3);
        }

        .character-info {
            flex: 1;
        }

        .character-name {
            font-size: 1.3rem;
            font-weight: bold;
            color: #ffffff;
            margin-bottom: 5px;
        }

        .server-info {
            font-size: 0.95rem;
            color: #b0b0b0;
        }

        .activity-type {
            display: inline-block;
            padding: 5px 12px;
            background-color: #505050;
            border-radius: 6px;
            font-size: 0.85rem;
            margin-top: 8px;
            color: #e0e0e0;
            font-weight: 500;
        }

        .activity-content {
            margin-bottom: 18px;
        }

        .activity-title {
            font-weight: bold;
            margin-bottom: 10px;
            color: #ffffff;
            font-size: 1.2rem;
        }

        .activity-preview {
            font-size: 1rem;
            color: #c0c0c0;
            line-height: 1.5;
            max-height: 72px;
            overflow: hidden;
            text-overflow: ellipsis;
            display: -webkit-box;
            -webkit-line-clamp: 3;
            -webkit-box-orient: vertical;
        }

        .activity-meta {
            display: flex;
            justify-content: space-between;
            font-size: 0.9rem;
            color: #a0a0a0;
            border-top: 1px solid #404040;
            padding-top: 15px;
        }

        .badges {
            display: flex;
            flex-wrap: wrap;
            gap: 8px;
            margin-top: 15px;
        }

        .badge {
            background-color: #505050;
            padding: 4px 10px;
            border-radius: 4px;
            font-size: 0.75rem;
            color: #e0e0e0;
        }

        .loading {
            text-align: center;
            padding: 50px;
            font-size: 1.3rem;
            color: #b0b0b0;
        }

        .error {
            text-align: center;
            padding: 50px;
            color: #d0d0d0;
            font-size: 1.3rem;
        }

        .cover-image {
            max-width: 100%;
            margin-top: 15px;
            border-radius: 8px;
            max-height: 220px;
            object-fit: cover;
            box-shadow: 0 3px 10px rgba(0, 0, 0, 0.3);
        }

        /* 弹窗样式 */
        .modal {
            display: none;
            position: fixed;
            z-index: 1000;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            overflow: auto;
            background-color: rgba(0, 0, 0, 0.85);
        }

        .modal-content {
            background: linear-gradient(145deg, #2a2a2a, #333333);
            margin: 3% auto;
            padding: 30px;
            border-radius: 15px;
            width: 90%;
            max-width: 850px;
            max-height: 90vh;
            overflow-y: auto;
            box-shadow: 0 15px 35px rgba(0, 0, 0, 0.5);
            border: 1px solid #505050;
        }

        .modal-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 25px;
            border-bottom: 1px solid #505050;
            padding-bottom: 20px;
        }

        .modal-title {
            font-size: 1.8rem;
            color: #ffffff;
            font-weight: 600;
        }

        .close {
            color: #b0b0b0;
            font-size: 32px;
            font-weight: bold;
            cursor: pointer;
            transition: color 0.3s;
        }

        .close:hover,
        .close:focus {
            color: #ffffff;
            text-decoration: none;
        }

        .modal-body {
            display: flex;
            flex-direction: column;
            gap: 25px;
        }

        .modal-section {
            margin-bottom: 20px;
        }

        .modal-section h3 {
            font-size: 1.3rem;
            color: #ffffff;
            margin-bottom: 12px;
            border-bottom: 1px solid #505050;
            padding-bottom: 8px;
            font-weight: 600;
        }

        .modal-field {
            margin-bottom: 18px;
        }

        .modal-field-value {
            word-break: break-word;
            line-height: 1.6;
            color: #e0e0e0;
        }

        .modal-images {
            display: flex;
            flex-wrap: wrap;
            gap: 12px;
            margin-top: 15px;
        }

        .modal-image {
            max-width: 160px;
            max-height: 160px;
            border-radius: 8px;
            object-fit: cover;
            box-shadow: 0 3px 10px rgba(0, 0, 0, 0.3);
        }

        .modal-content-text {
            background-color: #2a2a2a;
            padding: 20px;
            border-radius: 8px;
            margin-top: 15px;
            overflow: hidden;
            border: 1px solid #404040;
        }

        /* HTML内容中的图片样式 */
        .modal-content-text img {
            max-width: 100%;
            height: auto;
            border-radius: 6px;
            margin: 12px 0;
            display: block;
            box-shadow: 0 3px 10px rgba(0, 0, 0, 0.3);
        }

        /* 表情图片特殊处理 */
        .modal-content-text img.emoji {
            max-width: 40px;
            display: inline-block;
            vertical-align: middle;
            margin: 0 4px;
        }

        .modal-character-info {
            display: flex;
            align-items: center;
            margin-bottom: 25px;
        }

        .modal-character-avatar {
            width: 90px;
            height: 90px;
            border-radius: 50%;
            object-fit: cover;
            margin-right: 25px;
            border: 4px solid #707070;
            box-shadow: 0 4px 15px rgba(0, 0, 0, 0.3);
        }

        .modal-character-details {
            flex: 1;
        }

        .modal-character-name {
            font-size: 1.7rem;
            font-weight: bold;
            color: #ffffff;
            margin-bottom: 8px;
        }

        .modal-character-server {
            font-size: 1.1rem;
            color: #b0b0b0;
        }

        .modal-activity-type {
            display: inline-block;
            padding: 6px 14px;
            background-color: #606060;
            border-radius: 6px;
            font-size: 1rem;
            margin-top: 8px;
            color: #ffffff;
            font-weight: 500;
        }

        /* 标签样式 */
        .label-container {
            display: flex;
            flex-wrap: wrap;
            gap: 8px;
            margin-top: 12px;
        }

        .label {
            background-color: #606060;
            color: #ffffff;
            padding: 5px 12px;
            border-radius: 15px;
            font-size: 0.85rem;
            font-weight: 500;
        }

        /* 滚动加载相关样式 */
        .load-more-container {
            text-align: center;
            padding: 30px;
        }

        .load-more-btn {
            padding: 12px 30px;
            background-color: #606060;
            color: #ffffff;
            border: none;
            border-radius: 8px;
            cursor: pointer;
            font-size: 1rem;
            transition: all 0.3s ease;
        }

        .load-more-btn:hover {
            background-color: #707070;
            transform: translateY(-2px);
        }

        .load-more-btn:disabled {
            background-color: #404040;
            cursor: not-allowed;
            transform: none;
        }

        .loading-more {
            display: inline-block;
            width: 20px;
            height: 20px;
            border: 3px solid rgba(255, 255, 255, 0.3);
            border-radius: 50%;
            border-top-color: #ffffff;
            animation: spin 1s ease-in-out infinite;
            margin-right: 10px;
            vertical-align: middle;
        }

        @keyframes spin {
            to { transform: rotate(360deg); }
        }

        .no-more-data {
            color: #b0b0b0;
            font-size: 1rem;
            padding: 20px;
            text-align: center;
        }

        @media (max-width: 768px) {
            .activity-list {
                grid-template-columns: 1fr;
            }

            .controls {
                flex-direction: column;
            }

            .filter-controls {
                justify-content: center;
            }

            .modal-content {
                width: 95%;
                margin: 5% auto;
                padding: 20px;
            }

            .modal-character-info {
                flex-direction: column;
                text-align: center;
            }

            .modal-character-avatar {
                margin-right: 0;
                margin-bottom: 20px;
            }

            /* 移动端图片样式调整 */
            .modal-content-text img {
                max-width: 100%;
                height: auto;
            }

            h1 {
                font-size: 2.2rem;
            }

            .subtitle {
                font-size: 1.1rem;
            }
        }
    </style>
</head>
<body>
<div class="container">
    <header>
        <h1>Feed & Post</h1>
        <p class="subtitle">Phantoms FC 成员最新动态</p>
    </header>

    <div class="controls">
        <div class="filter-controls">
            <select id="filter-type">
                <option value="all">全部类型</option>
                <option value="post">帖子</option>
                <option value="recruit">招募</option>
                <option value="rp">RP活动</option>
            </select>
            <select id="sort-by">
                <option value="newest">最新发布</option>
                <option value="oldest">最早发布</option>
                <option value="popular">最受欢迎</option>
            </select>
        </div>
        <button id="refresh-btn">刷新数据</button>
    </div>

    <div class="stats">
        <div class="stat-item">
            <div class="stat-value" id="total-count">0</div>
            <div class="stat-label">Total</div>
        </div>
        <div class="stat-item">
            <div class="stat-value" id="post-count">0</div>
            <div class="stat-label">帖子</div>
        </div>
        <div class="stat-item">
            <div class="stat-value" id="recruit-count">0</div>
            <div class="stat-label">招募</div>
        </div>
        <div class="stat-item">
            <div class="stat-value" id="rp-count">0</div>
            <div class="stat-label">RP活动</div>
        </div>
    </div>

    <div id="activity-container">
        <div class="loading">正在加载数据...</div>
    </div>

    <!-- 滚动加载更多区域 -->
    <div id="load-more-container" class="load-more-container" style="display: none;">
        <button id="load-more-btn" class="load-more-btn">
            <span class="loading-more" style="display: none;"></span>
            加载更多
        </button>
        <div id="no-more-data" class="no-more-data" style="display: none;">没有更多数据了</div>
    </div>
</div>

<!-- 弹窗 -->
<div id="detailModal" class="modal">
    <div class="modal-content">
        <div class="modal-header">
            <h2 class="modal-title">动态详情</h2>
            <span class="close">&times;</span>
        </div>
        <div class="modal-body" id="modalBody">
            <!-- 动态详情内容将通过JavaScript填充 -->
        </div>
    </div>
</div>

<script>
    // API端点
    const API_URL = 'https://phantoms-backend.onrender.com/api/risingstones/guild-member-dynamic';

    // 图片代理服务 - 使用images.weserv.nl
    const IMAGE_PROXY_URL = 'https://images.weserv.nl/?url=';

    // 默认头像
    const DEFAULT_AVATAR = '';

    // 全局变量存储数据
    let activitiesData = [];
    let filteredData = [];

    // 分页相关变量
    let currentPage = 1;
    let hasMoreData = true;
    let isLoading = false;
    let currentFilterType = 'all';
    let currentSortBy = 'newest';

    // 页面加载完成后获取数据
    document.addEventListener('DOMContentLoaded', function() {
        // 初始加载第一页数据
        fetchData(1, true);

        // 添加事件监听器
        document.getElementById('filter-type').addEventListener('change', function() {
            currentFilterType = this.value;
            currentPage = 1;
            hasMoreData = true;
            filterAndSortActivities(true);
        });

        document.getElementById('sort-by').addEventListener('change', function() {
            currentSortBy = this.value;
            currentPage = 1;
            hasMoreData = true;
            filterAndSortActivities(true);
        });

        document.getElementById('refresh-btn').addEventListener('click', function() {
            currentPage = 1;
            hasMoreData = true;
            fetchData(1, true);
        });

        // 加载更多按钮事件
        document.getElementById('load-more-btn').addEventListener('click', function() {
            if (!isLoading && hasMoreData) {
                fetchData(currentPage + 1, false);
            }
        });

        // 弹窗关闭事件
        document.querySelector('.close').addEventListener('click', closeModal);
        window.addEventListener('click', function(event) {
            const modal = document.getElementById('detailModal');
            if (event.target === modal) {
                closeModal();
            }
        });

        // 滚动加载监听
        window.addEventListener('scroll', handleScroll);
    });

    // 滚动加载处理
    function handleScroll() {
        // 如果正在加载或没有更多数据，则不处理
        if (isLoading || !hasMoreData) return;

        // 计算距离底部的距离
        const scrollTop = window.pageYOffset || document.documentElement.scrollTop;
        const windowHeight = window.innerHeight;
        const documentHeight = document.documentElement.scrollHeight;

        // 当滚动到距离底部200px以内时，自动加载更多
        if (scrollTop + windowHeight >= documentHeight - 200) {
            fetchData(currentPage + 1, false);
        }
    }

    // 获取数据函数
    async function fetchData(page = 1, isRefresh = false) {
        // 防止重复请求
        if (isLoading) return;

        isLoading = true;

        // 显示加载状态
        if (isRefresh) {
            const container = document.getElementById('activity-container');
            container.innerHTML = '<div class="loading">正在加载数据...</div>';
            hideLoadMoreButton();
        } else {
            // 只有在有加载更多按钮时才显示加载状态
            const loadMoreBtn = document.getElementById('load-more-btn');
            if (loadMoreBtn && loadMoreBtn.style.display !== 'none') {
                showLoadingMore();
            }
        }

        try {
            const response = await fetch(`${API_URL}?page=${page}&limit=10`);
            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }
            const data = await response.json();

            if (data.code === 10000) {
                const newActivities = data.data.rows;

                // 检查是否还有更多数据
                if (newActivities.length === 0) {
                    hasMoreData = false;
                    showNoMoreData();
                } else {
                    currentPage = page;

                    if (isRefresh) {
                        // 刷新时替换所有数据
                        activitiesData = newActivities;
                        updateStats(data); // 传入完整的data对象
                        filterAndSortActivities(true);
                    } else {
                        // 加载更多时追加数据
                        activitiesData = [...activitiesData, ...newActivities];
                        // 对于加载更多，我们仍然使用API返回的总数
                        updateStats(data);
                        filterAndSortActivities(false);
                    }

                    hasMoreData = true;
                }
            } else {
                throw new Error(`API error: ${data.msg}`);
            }
        } catch (error) {
            console.error('Error fetching data:', error);
            if (isRefresh) {
                const container = document.getElementById('activity-container');
                container.innerHTML = `<div class="error">加载数据失败: ${error.message}</div>`;
            }
            hasMoreData = true;
        } finally {
            isLoading = false;
            hideLoadingMore();

            // 只有在有更多数据且不是刷新操作时才显示加载更多按钮
            if (hasMoreData && !isRefresh) {
                showLoadMoreButton();
            }
        }
    }

    // 更新统计信息
    function updateStats(data) {
        // 使用API返回的count作为Total值，添加安全检查
        let totalCount = 0;
        if (data && data.data && data.data.count) {
            totalCount = parseInt(data.data.count);
        } else {
            totalCount = activitiesData.length;
        }
        document.getElementById('total-count').textContent = totalCount;

        // 其他统计保持不变
        const postCount = activitiesData.filter(activity => activity.from === 2).length;
        const recruitCount = activitiesData.filter(activity =>
            activity.from === 5 || activity.from === 6 || activity.from === 9 || activity.from === 7).length;
        const rpCount = activitiesData.filter(activity => activity.from === 8).length;

        document.getElementById('post-count').textContent = postCount;
        document.getElementById('recruit-count').textContent = recruitCount;
        document.getElementById('rp-count').textContent = rpCount;
    }

    // 过滤和排序活动
    function filterAndSortActivities(resetPagination = true) {
        if (resetPagination) {
            currentPage = 1;
            hasMoreData = true;
        }

        // 过滤数据
        if (currentFilterType === 'all') {
            filteredData = [...activitiesData];
        } else if (currentFilterType === 'post') {
            filteredData = activitiesData.filter(activity => activity.from === 2);
        } else if (currentFilterType === 'recruit') {
            filteredData = activitiesData.filter(activity =>
                activity.from === 5 || activity.from === 6 || activity.from === 9 || activity.from === 7);
        } else if (currentFilterType === 'rp') {
            filteredData = activitiesData.filter(activity => activity.from === 8);
        }

        // 排序数据
        if (currentSortBy === 'newest') {
            filteredData.sort((a, b) => new Date(b.created_at) - new Date(a.created_at));
        } else if (currentSortBy === 'oldest') {
            filteredData.sort((a, b) => new Date(a.created_at) - new Date(b.created_at));
        } else if (currentSortBy === 'popular') {
            filteredData.sort((a, b) => {
                const aLikes = parseInt(a.like_count) || 0;
                const bLikes = parseInt(b.like_count) || 0;
                return bLikes - aLikes;
            });
        }

        displayActivities();
    }

    // 显示活动
    function displayActivities() {
        const container = document.getElementById('activity-container');

        if (filteredData.length === 0) {
            container.innerHTML = '<div class="loading">没有找到匹配的活动</div>';
            hideLoadMoreButton();
            return;
        }

        container.innerHTML = '<div class="activity-list"></div>';
        const activityList = container.querySelector('.activity-list');

        filteredData.forEach(activity => {
            const activityCard = createActivityCard(activity);
            activityList.appendChild(activityCard);
        });

        // 如果有更多数据，显示加载更多按钮
        if (hasMoreData) {
            showLoadMoreButton();
        } else {
            showNoMoreData();
        }
    }

    // 创建活动卡片
    function createActivityCard(activity) {
        const card = document.createElement('div');
        card.className = 'activity-card';
        card.dataset.activity = JSON.stringify(activity);

        // 解析徽章数据
        let badges = [];
        try {
            if (activity.badge && activity.badge !== '[]') {
                badges = JSON.parse(activity.badge);
            }
        } catch (e) {
            console.error('Error parsing badges:', e);
            badges = [];
        }

        // 获取活动类型和内容
        const { typeText, title, content, coverImage } = getActivityDetails(activity);

        // 使用代理处理图片URL
        const avatarUrl = activity.avatar ? getProxiedImageUrl(activity.avatar) : DEFAULT_AVATAR;
        const coverUrl = coverImage ? getProxiedImageUrl(coverImage) : null;

        card.innerHTML = `
            <div class="activity-header">
                <img src="${avatarUrl}" alt="头像" class="avatar" onerror="this.src='${DEFAULT_AVATAR}'">
                <div class="character-info">
                    <div class="character-name">${activity.character_name}</div>
                    <div class="server-info">${activity.area_name} · ${activity.group_name}</div>
                    <span class="activity-type">${typeText}</span>
                </div>
            </div>

            <div class="activity-content">
                <div class="activity-title">${title || '无标题'}</div>
                <div class="activity-preview">${content}</div>
                ${coverUrl ? `<img src="${coverUrl}" class="cover-image" alt="封面" onerror="this.style.display='none'">` : ''}
            </div>

            ${badges.length > 0 ? `
            <div class="badges">
                ${badges.slice(0, 3).map(badge =>
            `<span class="badge">${badge.badgeName}</span>`
        ).join('')}
                ${badges.length > 3 ? `<span class="badge">+${badges.length - 3}更多</span>` : ''}
            </div>
            ` : ''}

            <div class="activity-meta">
                <div>${formatDate(activity.created_at)}</div>
                <div>❤️ ${activity.like_count} · 💬 ${activity.comment_count}</div>
            </div>
        `;

        // 添加点击事件打开弹窗
        card.addEventListener('click', function() {
            openModal(activity);
        });

        return card;
    }

    // 打开弹窗显示详细信息
    function openModal(activity) {
        const modal = document.getElementById('detailModal');
        const modalBody = document.getElementById('modalBody');

        // 清空之前的内容
        modalBody.innerHTML = '';

        // 创建角色信息部分
        const characterInfoSection = createCharacterInfoSection(activity);
        modalBody.appendChild(characterInfoSection);

        // 创建活动内容部分
        const contentSection = createContentSection(activity);
        modalBody.appendChild(contentSection);

        // 如果有额外信息，创建详细信息部分
        const detailSection = createDetailSection(activity);
        if (detailSection) {
            modalBody.appendChild(detailSection);
        }

        // 显示弹窗
        modal.style.display = 'block';
    }

    // 创建角色信息部分
    function createCharacterInfoSection(activity) {
        const section = document.createElement('div');
        section.className = 'modal-section';

        const avatarUrl = activity.avatar ? getProxiedImageUrl(activity.avatar) : DEFAULT_AVATAR;
        const { typeText } = getActivityDetails(activity);

        section.innerHTML = `
            <div class="modal-character-info">
                <img src="${avatarUrl}" alt="头像" class="modal-character-avatar" onerror="this.src='${DEFAULT_AVATAR}'">
                <div class="modal-character-details">
                    <div class="modal-character-name">${activity.character_name}</div>
                    <div class="modal-character-server">${activity.area_name} · ${activity.group_name}</div>
                    <span class="modal-activity-type">${typeText}</span>
                </div>
            </div>
            <div class="activity-meta">
                <div>发布于 ${formatFullDate(activity.created_at)}</div>
                <div>❤️ ${activity.like_count} 个赞 · 💬 ${activity.comment_count} 条评论</div>
            </div>
        `;

        return section;
    }

    // 创建内容部分
    function createContentSection(activity) {
        const section = document.createElement('div');
        section.className = 'modal-section';

        const { title, content, coverImage } = getActivityDetails(activity);

        // 处理HTML内容中的图片代理和样式
        let processedContent = content;
        if (processedContent) {
            // 先处理表情标记
            processedContent = convertEmojiTags(processedContent);

            // 再处理其他HTML内容
            if (processedContent.includes('<img') || processedContent.includes('src=')) {
                processedContent = processHtmlImages(processedContent);
            }
        }

        // 对于mask_content也需要单独处理（针对case 1的情况）
        let maskContentHtml = '';
        if (activity.mask_content) {
            let processedMaskContent = convertEmojiTags(activity.mask_content);
            if (processedMaskContent.includes('<img') || processedMaskContent.includes('src=')) {
                processedMaskContent = processHtmlImages(processedMaskContent);
            }
            maskContentHtml = processedMaskContent;
        }

        // 处理封面图片
        let imagesHtml = '';
        if (coverImage) {
            const images = coverImage.split(',');
            imagesHtml = `
                <div class="modal-images">
                    ${images.map(img => `
                        <img src="${getProxiedImageUrl(img)}" class="modal-image" alt="内容图片"
                             onerror="this.style.display='none'">
                    `).join('')}
                </div>
            `;
        }

        section.innerHTML = `
            <h3>内容详情</h3>
            ${title ? `<div class="modal-field"><div class="modal-field-value" style="font-weight: bold; font-size: 1.2rem; margin-bottom: 10px;">${title}</div></div>` : ''}
            ${processedContent || maskContentHtml ? `
                <div class="modal-content-text">
                    ${processedContent || maskContentHtml}
                </div>
            ` : '<div class="modal-content-text">暂无详细内容</div>'}
            ${imagesHtml}
        `;

        return section;
    }

    // 创建详细信息部分
    function createDetailSection(activity) {
        if (!activity.from_info) return null;

        const section = document.createElement('div');
        section.className = 'modal-section';

        let detailsHtml = '';

        // 根据活动类型显示不同的详细信息
        switch(activity.from) {
            case 1: // 普通动态
                if (activity.mask_content) {
                    // 处理表情标记
                    let processedMaskContent = convertEmojiTags(activity.mask_content);
                    if (processedMaskContent.includes('<img') || processedMaskContent.includes('src=')) {
                        processedMaskContent = processHtmlImages(processedMaskContent);
                    }

                    detailsHtml += `
                    <div class="modal-field">
                        <div class="modal-field-value">动态内容：</div>
                        <div class="modal-content-text">${processedMaskContent}</div>
                    </div>
                    `;
                }
                // 处理动态图片
                if (activity.pic_url) {
                    const images = activity.pic_url.split(',');
                    detailsHtml += `
                    <div class="modal-field">
                        <div class="modal-field-value">图片：</div>
                        <div class="modal-images">
                            ${images.map(img => `
                                <img src="${getProxiedImageUrl(img)}" class="modal-image" alt="动态图片"
                                     onerror="this.style.display='none'">
                            `).join('')}
                        </div>
                    </div>
                    `;
                }
                break;
            case 2: // 帖子
            case 5: // 导师招募
            case 9: // 其他招募
            case 6: // 副本招募
                if (activity.from_info.fb_name) {
                    detailsHtml += `<div class="modal-field"><div class="modal-field-value">副本：${activity.from_info.fb_name}</div></div>`;
                }
                if (activity.from_info.progress) {
                    detailsHtml += `<div class="modal-field"><div class="modal-field-value">进度：${activity.from_info.progress}</div></div>`;
                }
                if (activity.from_info.fb_time) {
                    detailsHtml += `<div class="modal-field"><div class="modal-field-value">时间：${activity.from_info.fb_time}</div></div>`;
                }
                if (activity.from_info.team_composition) {
                    detailsHtml += `<div class="modal-field"><div class="modal-field-value">队伍构成：${activity.from_info.team_composition}</div></div>`;
                }
                if (activity.from_info.strategy) {
                    detailsHtml += `<div class="modal-field"><div class="modal-field-value">攻略：${activity.from_info.strategy}</div></div>`;
                }
                if (activity.from_info.labelInfo) {
                    detailsHtml += `<div class="modal-field"><div class="modal-field-value">标签：</div><div class="label-container">${activity.from_info.labelInfo.map(label => `<span class="label">${label.name}</span>`).join('')}</div></div>`;
                }
                break;

            case 7: // 分享招募
                if (activity.from_info.guild_name) {
                    detailsHtml += `<div class="modal-field"><div class="modal-field-value">部队：${activity.from_info.guild_name}</div></div>`;
                }
                if (activity.from_info.guild_tag) {
                    detailsHtml += `<div class="modal-field"><div class="modal-field-value">部队简称：${activity.from_info.guild_tag}</div></div>`;
                }
                if (activity.from_info.active_member_num) {
                    detailsHtml += `<div class="modal-field"><div class="modal-field-value">活跃成员：${activity.from_info.active_member_num}人</div></div>`;
                }
                if (activity.from_info.target_recruit_num) {
                    detailsHtml += `<div class="modal-field"><div class="modal-field-value">目标招募：${activity.from_info.target_recruit_num}人</div></div>`;
                }
                if (activity.from_info.weekend_time && activity.from_info.weekend_time !== '00:00-00:00') {
                    detailsHtml += `<div class="modal-field"><div class="modal-field-value">周末活跃时间：${activity.from_info.weekend_time}</div></div>`;
                }
                if (activity.from_info.weekday_time && activity.from_info.weekday_time !== '00:00-00:00') {
                    detailsHtml += `<div class="modal-field"><div class="modal-field-value">工作日活跃时间：${activity.from_info.weekday_time}</div></div>`;
                }
                if (activity.from_info.labelInfo && activity.from_info.labelInfo.length > 0) {
                    detailsHtml += `<div class="modal-field"><div class="modal-field-value">标签：</div><div class="label-container">${activity.from_info.labelInfo.map(label => `<span class="label">${label.name}</span>`).join('')}</div></div>`;
                }
                if (activity.from_info.detail_mask) {
                    // 处理detail_mask中的表情标记
                    let processedDetailMask = convertEmojiTags(activity.from_info.detail_mask);
                    if (processedDetailMask.includes('<img') || processedDetailMask.includes('src=')) {
                        processedDetailMask = processHtmlImages(processedDetailMask);
                    }

                    detailsHtml += `
                    <div class="modal-field">
                        <div class="modal-field-value">详情：</div>
                        <div class="modal-content-text" id="detail-mask-content-${activity.id}">
                            ${processedDetailMask}
                        </div>
                    </div>
                    `;
                }
                break;

            case 8: // RP活动
                if (activity.from_info.rp_name) {
                    detailsHtml += `<div class="modal-field"><div class="modal-field-value">活动名称：${activity.from_info.rp_name}</div></div>`;
                }
                if (activity.from_info.profile) {
                    detailsHtml += `<div class="modal-field"><div class="modal-field-value">活动简介：${activity.from_info.profile}</div></div>`;
                }
                if (activity.from_info.start_time) {
                    detailsHtml += `<div class="modal-field"><div class="modal-field-value">开始时间：${formatFullDate(activity.from_info.start_time)}</div></div>`;
                }
                if (activity.from_info.address) {
                    detailsHtml += `<div class="modal-field"><div class="modal-field-value">地址：${activity.from_info.address}</div></div>`;
                }
                if (activity.from_info.open_time) {
                    detailsHtml += `<div class="modal-field"><div class="modal-field-value">开放时间：${activity.from_info.open_time}</div></div>`;
                }
                if (activity.from_info.custom_label) {
                    const labels = activity.from_info.custom_label.split(',');
                    detailsHtml += `<div class="modal-field"><div class="modal-field-value">标签：</div><div class="label-container">${labels.map(label => `<span class="label">${label}</span>`).join('')}</div></div>`;
                }
                // 处理detail_mask中的图片和表情
                if (activity.from_info.detail_mask) {
                    // 处理detail_mask中的表情标记
                    let processedDetailMask = convertEmojiTags(activity.from_info.detail_mask);
                    if (processedDetailMask.includes('<img') || processedDetailMask.includes('src=')) {
                        processedDetailMask = processHtmlImages(processedDetailMask);
                    }

                    detailsHtml += `
                    <div class="modal-field">
                        <div class="modal-field-value">活动详情：</div>
                        <div class="modal-content-text" id="detail-mask-content-${activity.id}">
                            ${processedDetailMask}
                        </div>
                    </div>
                    `;
                }
                break;
        }

        if (!detailsHtml) return null;

        section.innerHTML = `
            <h3>活动详情</h3>
            ${detailsHtml}
        `;

        // 在DOM插入后处理图片
        setTimeout(() => {
            processImagesInElement(section, activity.id);
        }, 0);

        return section;
    }

    // 处理元素内的所有图片
    function processImagesInElement(element, activityId) {
        const contentElement = element.querySelector(`#detail-mask-content-${activityId}`);
        if (!contentElement) return;

        const images = contentElement.querySelectorAll('img');
        images.forEach(img => {
            const originalSrc = img.getAttribute('src');
            if (originalSrc && !originalSrc.startsWith('data:') && !originalSrc.includes('weserv.nl')) {
                const proxiedSrc = getProxiedImageUrl(originalSrc);
                img.setAttribute('src', proxiedSrc);

                // 移除原有的width/height属性，让CSS控制尺寸
                img.removeAttribute('width');
                img.removeAttribute('height');

                // 添加错误处理
                img.onerror = function() {
                    console.warn('代理图片加载失败，尝试使用原始URL:', originalSrc);
                    this.setAttribute('src', originalSrc);

                    // 如果原始图片也加载失败，隐藏图片
                    this.onerror = function() {
                        this.style.display = 'none';
                    };
                };
            }
        });
    }

    // 关闭弹窗
    function closeModal() {
        const modal = document.getElementById('detailModal');
        modal.style.display = 'none';
    }

    // 表情标记转换函数
    function convertEmojiTags(text) {
        if (!text) return text;

        // 将表情标记 [emo19] 转换为图片标签
        // 正则表达式匹配 [emo数字] 格式
        return text.replace(/\[emo(\d+)\]/g, function(match, emojiId) {
            // 构建表情图片URL
            const emojiUrl = `https://static.web.sdo.com/jijiamobile/pic/ff14/2023ffstone/emo${emojiId}.png`;
            // 使用代理URL
            const proxiedUrl = getProxiedImageUrl(emojiUrl);

            // 返回图片标签，设置合适的大小
            return `<img src="${proxiedUrl}" alt="表情${emojiId}" class="emoji" onerror="this.style.display='none'">`;
        });
    }

    // 获取代理图片URL
    function getProxiedImageUrl(originalUrl) {
        // 如果已经是代理URL，直接返回
        if (originalUrl.includes('weserv.nl')) {
            return originalUrl;
        }

        // 使用images.weserv.nl代理服务
        return `${IMAGE_PROXY_URL}${encodeURIComponent(originalUrl)}`;
    }

    // 处理HTML内容中的图片代理和样式
    function processHtmlImages(htmlContent) {
        if (!htmlContent) return htmlContent;

        // 创建临时DOM元素来解析和修改HTML
        const tempDiv = document.createElement('div');
        tempDiv.innerHTML = htmlContent;

        // 处理所有img标签
        const images = tempDiv.querySelectorAll('img');
        images.forEach(img => {
            const originalSrc = img.getAttribute('src');
            if (originalSrc && !originalSrc.startsWith('data:')) { // 排除data URI
                const proxiedSrc = getProxiedImageUrl(originalSrc);
                img.setAttribute('src', proxiedSrc);

                // 移除原有的width/height属性，让CSS控制尺寸
                img.removeAttribute('width');
                img.removeAttribute('height');

                // 添加错误处理
                img.onerror = function() {
                    console.warn('代理图片加载失败，尝试使用原始URL:', originalSrc);
                    this.setAttribute('src', originalSrc);

                    // 如果原始图片也加载失败，隐藏图片
                    this.onerror = function() {
                        this.style.display = 'none';
                    };
                };
            }
        });

        return tempDiv.innerHTML;
    }

    // 获取活动详情
    function getActivityDetails(activity) {
        let typeText = '未知';
        let title = '';
        let content = '';
        let coverImage = '';

        // 根据from字段判断活动类型
        switch(activity.from) {
            case 1: // 普通动态
                typeText = '发布了动态';
                // 移除表情标记用于预览
                content = activity.mask_content ?
                    activity.mask_content.replace(/\[emo\d+\]/g, '[表情]') : '';
                coverImage = activity.pic_url || '';
                break;
            case 2: // 帖子
                typeText = '发表了帖子';
                if (activity.from_info) {
                    title = activity.from_info.title;
                    content = activity.from_info.content_pre || '';
                    coverImage = activity.from_info.cover_pic || '';
                }
                break;
            case 5: // 导师招募
                typeText = '发布了导师招募';
                if (activity.from_info) {
                    title = activity.from_info.title;
                    content = activity.from_info.detail_mask ?
                        activity.from_info.detail_mask.replace(/<[^>]*>/g, '').substring(0, 100) + '...' : '';
                }
                break;
            case 6: // 副本招募
                typeText = '发布了副本招募';
                if (activity.from_info) {
                    title = activity.from_info.fb_name;
                    content = activity.from_info.progress || '';
                }
                break;
            case 7: // 分享招募
                typeText = '分享了招募';
                if (activity.from_info) {
                    title = (activity.from_info.guild_name || '') + (activity.from_info.guild_tag ? ` <${activity.from_info.guild_tag}>` : '');
                    content = activity.from_info.detail_mask ?
                        activity.from_info.detail_mask.replace(/<[^>]*>/g, '').substring(0, 100) + '...' : '';
                    coverImage = activity.from_info.cover_pic || '';
                }
                break;
            case 8: // RP活动
                typeText = '发布了RP活动';
                if (activity.from_info) {
                    title = activity.from_info.rp_name;
                    content = activity.from_info.profile || '';
                    coverImage = activity.from_info.cover_pic || '';
                }
                break;
            case 9: // 其他招募
                typeText = '发布了招募';
                if (activity.from_info) {
                    title = activity.from_info.title;
                    content = activity.from_info.detail_mask ?
                        activity.from_info.detail_mask.replace(/<[^>]*>/g, '').substring(0, 100) + '...' : '';
                }
                break;
            default:
                typeText = activity.mask_content || '发布了内容';
        }

        // 如果内容为空，使用mask_content（但需要过滤掉无意义的默认文本）
        if (!content && activity.mask_content) {
            const meaninglessTexts = ['发表了帖子：', '发布了招募：', '发布了RP：', '上架了招募：', '分享招募-'];
            const isMeaningless = meaninglessTexts.some(text => activity.mask_content.includes(text));

            if (!isMeaningless) {
                content = activity.mask_content;
            }
        }

        // 处理HTML标签，提取纯文本用于预览
        if (content && content.includes('<')) {
            content = content.replace(/<[^>]*>/g, '');
        }

        // 限制内容长度
        if (content && content.length > 100) {
            content = content.substring(0, 100) + '...';
        }

        return { typeText, title, content, coverImage };
    }

    // 日期格式化函数
    function formatDate(dateString) {
        const date = new Date(dateString);
        const now = new Date();
        const diffMs = now - date;
        const diffMins = Math.floor(diffMs / (1000 * 60));
        const diffHours = Math.floor(diffMs / (1000 * 60 * 60));
        const diffDays = Math.floor(diffMs / (1000 * 60 * 60 * 24));

        if (diffMins < 1) {
            return '刚刚';
        } else if (diffMins < 60) {
            return `${diffMins}分钟前`;
        } else if (diffHours < 24) {
            return `${diffHours}小时前`;
        } else if (diffDays < 7) {
            return `${diffDays}天前`;
        } else {
            return date.toLocaleDateString('zh-CN', {
                year: 'numeric',
                month: 'short',
                day: 'numeric'
            });
        }
    }

    // 完整日期格式化函数
    function formatFullDate(dateString) {
        const date = new Date(dateString);
        return date.toLocaleString('zh-CN', {
            year: 'numeric',
            month: 'long',
            day: 'numeric',
            hour: '2-digit',
            minute: '2-digit'
        });
    }

    // 显示加载更多按钮
    function showLoadMoreButton() {
        const container = document.getElementById('load-more-container');
        const button = document.getElementById('load-more-btn');
        const noMoreData = document.getElementById('no-more-data');

        container.style.display = 'block';
        button.style.display = 'inline-block';
        noMoreData.style.display = 'none';
    }

    // 隐藏加载更多按钮
    function hideLoadMoreButton() {
        const container = document.getElementById('load-more-container');
        container.style.display = 'none';
    }

    // 显示加载中状态
    function showLoadingMore() {
        const button = document.getElementById('load-more-btn');
        // 检查按钮是否存在且可见
        if (!button || button.style.display === 'none') {
            return; // 如果按钮不存在或隐藏，直接返回
        }

        const loadingIcon = button.querySelector('.loading-more');

        button.disabled = true;
        if (loadingIcon) {
            loadingIcon.style.display = 'inline-block';
        }
        button.innerHTML = '<span class="loading-more"></span> 加载中...';
    }

    // 隐藏加载中状态
    function hideLoadingMore() {
        const button = document.getElementById('load-more-btn');
        // 检查按钮是否存在
        if (!button) {
            return;
        }

        button.disabled = false;
        button.innerHTML = '加载更多';
    }

    // 修改滚动加载处理函数，添加更严格的检查
    function handleScroll() {
        // 如果正在加载或没有更多数据，或加载更多按钮不存在，则不处理
        if (isLoading || !hasMoreData) return;

        const loadMoreBtn = document.getElementById('load-more-btn');
        if (!loadMoreBtn || loadMoreBtn.style.display === 'none') {
            return;
        }

        // 计算距离底部的距离
        const scrollTop = window.pageYOffset || document.documentElement.scrollTop;
        const windowHeight = window.innerHeight;
        const documentHeight = document.documentElement.scrollHeight;

        // 当滚动到距离底部200px以内时，自动加载更多
        if (scrollTop + windowHeight >= documentHeight - 200) {
            fetchData(currentPage + 1, false);
        }
    }

    // 显示没有更多数据
    function showNoMoreData() {
        const container = document.getElementById('load-more-container');
        const button = document.getElementById('load-more-btn');
        const noMoreData = document.getElementById('no-more-data');

        container.style.display = 'block';
        button.style.display = 'none';
        noMoreData.style.display = 'block';
    }
</script>

<!-- 引入访客统计模块 -->
<script src="../visitor-tracker.js"></script>
<!-- Cloudflare Web Analytics -->
<script defer src='../lib/cloudflare/beacon.min.js' data-cf-beacon='{"token": "0e55e488041949479a3dace73ef940cd"}'>
</script>
<!-- End Cloudflare Web Analytics -->

</body>
</html>